package com.lwj.mapper;

import com.lwj.controller.test.HelloController;
import com.lwj.model.AuditModel;
import com.lwj.service.SpringUtil;
import com.lwj.utils.UuidUtil;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.annotation.Id;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Properties;

@Component
@Intercepts({
    @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class AuditInterceptor  implements Interceptor {
    protected static final Logger logger = LoggerFactory.getLogger(AuditInterceptor.class);
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];
        if(parameter instanceof AuditModel){
            Field[] fields = parameter.getClass().getDeclaredFields();
            for(Field field:fields){
                if(field.isAnnotationPresent(Id.class)&&SqlCommandType.INSERT == sqlCommandType){
                    initFieldValue(parameter,field,UuidUtil.getUuid());
                    break;
                }
            }
            String userEmpId = SpringUtil.getUserId();
            Class<?> superclass = parameter.getClass().getSuperclass();
            Field dr = superclass.getDeclaredField("dr");
            Field creator = superclass.getDeclaredField("creator");
            Field createTime = superclass.getDeclaredField("createTime");
            Field updateBy = superclass.getDeclaredField("updateBy");
            Field updateTime = superclass.getDeclaredField("updateTime");
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String currentTime = dtf.format(LocalDateTime.now());
            if(SqlCommandType.INSERT == sqlCommandType){
                initFieldValue(parameter,dr,"0");
                initFieldValue(parameter,creator,userEmpId);
                initFieldValue(parameter,createTime,currentTime);
                initFieldValue(parameter,updateBy,userEmpId);
                initFieldValue(parameter,updateTime,currentTime);
            }
            if(SqlCommandType.UPDATE == sqlCommandType){
                initFieldValue(parameter,updateBy,userEmpId);
                initFieldValue(parameter,updateTime,currentTime);
            }
        }
        return invocation.proceed();
    }
    public void initFieldValue(Object o,Field field,Object param){
        try{
            field.setAccessible(true);
            field.set(o, param);
            field.setAccessible(false);
        }catch (Exception e){
            logger.error("设置属性报错",e);
        }
    }
    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        } else {
            return target;
        }
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
